#include "EEMP_HAL.h"
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
typedef struct {
	bool scope_cfg_update;
	bool la_cfg_update;
	bool sig_gen_cfg_update;
}cfg_update_t;
struct {
	int8_t cha_buf[CHA_FIFO_SIZE];
	int8_t chb_buf[CHB_FIFO_SIZE];
}scope_buf;
bool ep2_empty()
{
	uint8_t stat;
	get_endpoint_status(&stat);
	if (stat & 0x1)
	{
		return true;
	}
	else
	{
		return false;
	}
}
void error_handle()
{
	char error[50];
	uint32_t nt_status = get_ep2_usbd_status_string(error);
	printf("%s\n%d\n", error, nt_status);
	getchar();
}
void main()
{
	bool result;
	uint8_t power_status;
	result = dev_init();
	result = get_power_status(&power_status);
	if (power_status == 0)
	{
		result = power_on_off_circuits();
	}
	fpga_global_reset();
	reset_ep8_buffer();
	reset_ep2_buffer();
	getchar();
//	set_trigger_position(500);
	set_trigger_source(1);
//	set_auto_trigger(0);
//	set_trigger_voltage_level(20);
//	set_trigger_mode(0);
	set_attenuation(3, 1);
	set_clk_div_factor(0);
	set_op_mode(2);
	cfg_update_t cfg_update;
	result = apply_new_settings(&cfg_update.scope_cfg_update, &cfg_update.sig_gen_cfg_update, &cfg_update.la_cfg_update);
	uint8_t ep_stat;
	do{
		get_endpoint_status(&ep_stat);
	} while ((ep_stat>>6)!=0x1);			// wait until all data transmitted to soc
	
	uint8_t header_buf[1024];
	uint32_t header_length;
	uint8_t buf[1024];
	uint32_t length;
	while (1)
	{
		length = 1024;
		while (ep2_empty());
		if (!read_ep2_data(buf, &length))
		{
			error_handle();
		}
		else
		{
			printf("%d\n", length);
		}
/*		if (!ep2_empty())
		{
			length = 1024;
			header_length = 1024;
			if (!read_ep2_data(header_buf,&header_length))
			{
				error_handle();
			}
			if (header_length != 4) getchar();
			uint8_t i = 0;
			for (i = 0; i < 8; i++)
			{
				while (ep2_empty());
				if (!read_ep2_data(buf, &length))
				{
					error_handle();
				}
			}
		}
		*/
	}
}